package com.xiaoxie.boot.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author xiaoxie
 * @create 2022-03-19 23:17
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("渲染视图完成之后执行...");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("控制器方法执行之后执行...");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("控制器方法执行之前执行...");
        //已经登录了就放行 否则进行拦截
        HttpSession session = request.getSession();
        if (session.getAttribute("name") == null) {
            //没有登录，跳转到登录页面进行登录操作
            response.sendRedirect(request.getContextPath() + "page/login.html");
            return false;
        }else {
            log.info("放行了用户" + session.getAttribute("name") + "的请求");
            return true;
        }
    }
}
